import React, { useState } from 'react';
import { Progress } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { TableProps } from 'antd';
import { getWorkDetailAPI } from '@/api/analysis';
import Icon from '@/components/SvgIcon';
import type { DataType } from '../type';
import './index.scss';
import { formatDuration } from '@/utils';
import Table from '@/components/table';

interface WorkDetail {
  [key: string | number]: API.WorkDetailResult[];
}
type Iprops = TableProps<DataType> & {
  deviceInfo: any;
};
const utilization = [
  {
    type: 'higher',
    name: '高负荷',
  },
  {
    type: 'normal',
    name: '正常',
  },
  {
    type: 'lower',
    name: '低负荷',
  },
];
const RecordTable: React.FC<Iprops> = ({ deviceInfo, ...props }) => {
  const columns: ColumnsType<DataType> = [
    {
      title: '日期',
      dataIndex: 'statisticsTime',
      key: 'statisticsTime',
      width: 150,
    },
    {
      title: '利用率',
      dataIndex: 'utilization',
      key: 'utilization',
      render: text => {
        let percent = Number((text * 100).toFixed(0));
        let color = '';
        let classPix = '';
        if (
          percent >= 0 &&
          percent < deviceInfo?.utilizationLowThreshold * 100
        ) {
          color = '#58585F';
          classPix = 'lower';
        } else if (percent > deviceInfo?.utilizationHighThreshold * 100) {
          classPix = 'higher';
          color = '#E34D59';
        } else {
          color = '#0DC191';
          classPix = 'normal';
        }
        return (
          <div className={['utilization-progress', classPix].join(' ')}>
            <Progress
              percent={percent}
              format={percent => (percent === 100 ? '100%' : `${percent}%`)}
              strokeColor={color}
            />
          </div>
        );
      },
    },
    {
      title: '工作时长',
      dataIndex: 'cumulativeWorkingHours',
      key: 'cumulativeWorkingHours',
      width: 200,
      render: text => {
        return <>{formatDuration(text as number)}</>;
      },
    },
    {
      title: '工作次数',
      dataIndex: 'cumulativeWorkingNum',
      key: 'cumulativeWorkingNum',
      width: 150,
    },
  ];
  const [workDetail, setWorkDetail] = useState<WorkDetail>({});
  const getWorkDetail = (expanded: boolean, record: DataType) => {
    if (expanded) {
      getWorkDetailAPI({
        deviceCode: record.deviceCode,
        startTime: record.statisticsTime,
        endTime: record.statisticsTime,
      }).then(res => {
        let result: WorkDetail = {};
        result[record.id] = res.data;
        setWorkDetail({ ...workDetail, ...result });
      });
    }
  };
  return (
    <>
      <div className="record-container">
        <h1>利用率详情</h1>
        <div className="utilization-status">
          {utilization.map((item, index) => {
            return (
              <p className={['status', item.type].join(' ')} key={index}>
                {item.name}
              </p>
            );
          })}
        </div>
      </div>
      <div className="record-table flex-auto">
        <Table
          columns={columns}
          rowKey="id"
          // scroll={{y: '100%'}}
          expandable={{
            expandedRowRender: record => {
              return (
                <div style={{ maxHeight: '160px', overflow: 'auto' }}>
                  {workDetail[record.id] &&
                    workDetail[record.id].map((item, index) => {
                      return (
                        <div
                          key={index}
                          style={{
                            display: 'flex',
                            margin: '8px 16px',
                            fontWeight: 'normal',
                          }}>
                          第 {index + 1} 次工作：
                          <span
                            style={{
                              fontVariantNumeric: 'tabular-nums',
                            }}>
                            {item.startTime?.split(' ')[1]}
                          </span>
                          <Icon
                            name="icon-delimiter"
                            style={{
                              color: '#C9CDD4',
                              margin: '0 15px 0',
                              verticalAlign: 'middle',
                            }}
                          />
                          <span
                            style={{
                              fontVariantNumeric: 'tabular-nums',
                            }}>
                            {item.endTime?.split(' ')[1]}
                          </span>
                          <p style={{ marginLeft: '32px' }}>
                            共计工作时长：
                            <span
                              style={{
                                fontVariantNumeric: 'tabular-nums',
                              }}>
                              {formatDuration(item.duration as number)}
                            </span>
                          </p>
                          {item.validDuration > -1 && (
                            <p style={{ marginLeft: '32px' }}>
                              有效工作时长：
                              <span
                                style={{
                                  fontVariantNumeric: 'tabular-nums',
                                }}>
                                {formatDuration(item.validDuration as number)}
                              </span>
                            </p>
                          )}
                        </div>
                      );
                    })}
                </div>
              );
            },
            rowExpandable: record => record.cumulativeWorkingNum !== 0,
            onExpand: getWorkDetail,
            expandIcon: ({ expanded, onExpand, record }) =>
              record.cumulativeWorkingNum !== 0 &&
              (expanded ? (
                <div onClick={e => onExpand(record, e)}>
                  <Icon name="icon-arrow-down" />
                </div>
              ) : (
                <div onClick={e => onExpand(record, e)}>
                  <Icon name="icon-arrow-right" />
                </div>
              )),
          }}
          {...props}
        />
      </div>
    </>
  );
};
export default RecordTable;
